package com.huawei.translate.provider;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huawei.translate.utils.HttpUtils;
import com.huawei.translate.utils.SystemConfig;
import com.huawei.translate.vo.translate.HuaWeiTranslateResponse;
import com.huawei.translate.vo.translate.TranslateRequest;
import com.huawei.translate.vo.translate.TranslateResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;

@Service
public class HuaWeiTranslateProvider implements TranslateProvider {

    private Gson gson = new GsonBuilder().create();

    private static final Logger LOG = Logger.getLogger(HuaWeiTranslateProvider.class);

    @Override
    public TranslateResponse translate(TranslateRequest request) {
        try {
            request = normalizeTranslateRequest(request);
            long startTime = System.currentTimeMillis();
            LOG.info("Receive request to translate from huawei 2012.");

            String content = sendTranslateRequest(request.getFrom(), request.getTo(), request.getText());

            HuaWeiTranslateResponse translateResponse = gson.fromJson(content, HuaWeiTranslateResponse.class);

            if (translateResponse.getStatus() != 0) {
                LOG.error("Request:" + request.toString() + "\tHuaWeiTranslateProvider\t Status:" + translateResponse.getStatus() + "\nContent:\t" + content);
                return null;
            }
            LOG.info("Receive transalte response from huawei 2012." +  translateResponse.getResult());
            LOG.info("Receive transalte response from huawei 2012. took:" + (System.currentTimeMillis() - startTime));
            return new TranslateResponse(HttpStatus.OK.value(), translateResponse.getResult());
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return null;
        }
    }

    @Override
    public String translate(String from, String to, String content, String key) {
        try {
            String translateResult = sendTranslateRequest(from, to, content);
            HuaWeiTranslateResponse translateResponse = gson.fromJson(translateResult, HuaWeiTranslateResponse.class);

            if (translateResponse.getStatus() != 0) {
                return null;
            }
            return translateResponse.getResult();
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return null;
        }
    }

    private String sendTranslateRequest(String from, String to, String text) throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        URIBuilder builder = new URIBuilder(SystemConfig.getProperty("huawei.translate"));
        builder.setParameter("name", SystemConfig.getProperty("huawei.translate-username"))
                .setParameter("from", from)
                .setParameter("to", to)
                .setParameter("content", text);

        HttpGet httpGet = new HttpGet(builder.build());

        httpGet.setConfig(setTimeoutConfig());

        LOG.info("Receive request to translate from huawei 2012." +  httpGet.getURI());
        CloseableHttpResponse response = httpClient.execute(httpGet);

        InputStream inputStream = response.getEntity().getContent();
        return HttpUtils.getContentFromInputStream(inputStream);
    }

    @Override
    public String toDescription() {
        return TranslateProviderType.HuaWei.getDescription();
    }

    public RequestConfig setTimeoutConfig() {
        int timeOut = Integer.parseUnsignedInt(SystemConfig.getProperty("route.huawei.timeout", "2000"));
        return RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
    }

    public TranslateRequest normalizeTranslateRequest(TranslateRequest request) {
        TranslateRequest normalize = new TranslateRequest();
        normalize.setAccessToken(request.getAccessToken());
        normalize.setText(request.getText());
        if ("zh-CHS".equals(request.getFrom())) {
            normalize.setFrom("zh");
        } else {
            normalize.setFrom(request.getFrom());
        }
        if ("zh-CHS".equals(request.getTo())) {
            normalize.setTo("zh");
        } else {
            normalize.setTo(request.getTo());

        }
        return normalize;
    }
}
